package org.example.se;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;


public class CsrfTokenServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession(true);
        String csrfToken = session.getAttribute("csrfToken") != null ? (String) session.getAttribute("csrfToken") : generateToken();
        session.setAttribute("csrfToken", csrfToken);
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print(csrfToken);
        out.flush();
    }

    private String generateToken() {
        // 生成一个随机的 token，例如使用 UUID
        return java.util.UUID.randomUUID().toString();
    }
}